package com.example.translateappjava.Service.YOLOAPI;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageGetter {

    // 定义一个回调接口，图片下载完成后可以通知调用者
    public interface ImageDownloadCallback {
        void onImageDownloaded(Bitmap bitmap);
        void onDownloadFailed(String errorMessage);
    }

    // 使用 GET 方法下载图片
    public void downloadImage(String imageUrl, ImageDownloadCallback callback) {
        new Thread(() -> {
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                InputStream inputStream = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                if (bitmap != null) {
                    // 图片下载成功，调用回调函数
                    callback.onImageDownloaded(bitmap);
                } else {
                    // 图片下载失败，调用回调函数
                    callback.onDownloadFailed("Failed to decode the image.");
                }
            } catch (Exception e) {
                e.printStackTrace();
                callback.onDownloadFailed("Error downloading image: " + e.getMessage());
            }
        }).start();
    }
}
